class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = "NotFoundError";
  }
}

const onSuccess = (res, message = "请求成功", data, code = 200) => {
  res.json({
    code,
    message,
    data,
  });
};

const onError = (res, error) => {
  if (error.name === "SequelizeValidationError") {
    const errors = error.errors.map((e) => e.message);
    res.json({
      code: 400,
      message: "请求参数错误",
      errors,
    });
  } else if (error.name === "NotFoundError") {
    res.json({
      code: 404,
      message: "接口不存在",
    });
  } else {
    res.json({
      code: 500,
      message: "服务器内部错误",
    });
  }
};

module.exports = {
  onError,
  onSuccess,
  NotFoundError,
};
